package cn.yh.nft.turbo.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.yh.nft.turbo.admin.infrastructure.exception.AdminException;
import cn.yh.nft.turbo.admin.param.AdminCollectionCreateParam;
import cn.yh.nft.turbo.admin.param.AdminCollectionModifyParam;
import cn.yh.nft.turbo.admin.param.AdminCollectionRemoveParam;
import cn.yh.nft.turbo.api.collection.model.CollectionVO;
import cn.yh.nft.turbo.api.collection.request.*;
import cn.yh.nft.turbo.api.collection.response.CollectionChainResponse;
import cn.yh.nft.turbo.api.collection.response.CollectionModifyResponse;
import cn.yh.nft.turbo.api.collection.response.CollectionRemoveResponse;
import cn.yh.nft.turbo.api.collection.service.CollectionManageFacadeService;
import cn.yh.nft.turbo.base.response.PageResponse;
import cn.yh.nft.turbo.base.utils.FileUtils;
import cn.yh.nft.turbo.file.FileService;
import cn.yh.nft.turbo.web.util.MultiResultConvertor;
import cn.yh.nft.turbo.web.vo.MultiResult;
import cn.yh.nft.turbo.web.vo.Result;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.h2.mvstore.DataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static cn.yh.nft.turbo.admin.infrastructure.exception.AdminErrorCode.ADMIN_UPLOAD_PICTURE_FAIL;

/**
 * @ClassName: CollectionAdminController
 * @Author: 草莓爱上啵啵
 * 藏品后台管理
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("admin/collection")
@CrossOrigin(origins = "*")
public class CollectionAdminController {

    @DubboReference(version = "1.0.0")
    private CollectionManageFacadeService collectionManageFacadeService;

    @Autowired
    private FileService fileService;

    /**
     * 上传藏品图片到阿里云oss中
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadCollection")
    public Result<String> uploadCollection(@RequestParam("file_data")MultipartFile file) throws Exception {
        if (null == file){
            throw new AdminException(ADMIN_UPLOAD_PICTURE_FAIL);
        }
        String userId = (String) StpUtil.getLoginId();

        //藏品封面上传到oss服务中
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            //这里默认文件路径都是jpg
            filename = UUID.randomUUID().toString() + ".jpg";
        }
        InputStream fileStream = file.getInputStream();
        String path = FileUtils.newCollectionImageSuffix(userId, filename);
        String url = fileService.upload(path, fileStream);
        //如果为null就是保存失败
        if (StringUtils.isBlank(url)){
            throw new AdminException(ADMIN_UPLOAD_PICTURE_FAIL);
        }

        //到这里保存成功
        return Result.success(url);

    }

    /**
     * 创建藏品
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("/createCollection")
    public Result<Long> createCollection(@Valid @RequestBody AdminCollectionCreateParam param) throws Exception{
        //或者到创建者id也就是当前登录人id
        String  userId = (String) StpUtil.getLoginId();

        //创建一个创建藏品请求对象
        CollectionCreateRequest request = new CollectionCreateRequest();
        //将幂等号设置为当前请求的唯一标识
        request.setIdentifier(UUID.randomUUID().toString());
        //设置价格
        request.setPrice(param.getPrice());
        //库存
        request.setQuantity(param.getQuantity());
        //名字
        request.setName(param.getName());
        //详情
        request.setDetail(param.getDetail());
        //封面
        request.setCover(param.getCover());
        //创建者id
        request.setCreatorId(userId);
        //创建时间
        request.setCreateTime(new Date());
        //格式化一个时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //将发售时间格式化为设置的时间格式的日期
        request.setSaleTime(sdf.parse(param.getSaleTime()));

        //远程调用藏品服务创建藏品
        CollectionChainResponse response = collectionManageFacadeService.create(request);

        if (response.getSuccess()) {
            return  Result.success(response.getCollectionId());
        }else {
            return Result.error(response.getResponseCode(), response.getResponseMessage());
        }

    }


    /**
     * 删除藏品
     * @param param
     * @return
     */
    @PostMapping("/removeCollection")
    public Result<Long> removeCollection(@Valid @RequestBody AdminCollectionRemoveParam param) {
        CollectionRemoveRequest request = new CollectionRemoveRequest();
        request.setIdentifier(UUID.randomUUID().toString());
        request.setCollectionId(param.getCollectionId());
        CollectionRemoveResponse response = collectionManageFacadeService.remove(request);
        if (response.getSuccess()){
            return Result.success(response.getCollectionId());
        }else {
            return Result.error(response.getResponseCode(), response.getResponseMessage());
        }
    }

    /**
     * 修改商品库存
     * @param param
     * @return
     */
    @PostMapping("/modifyInventory")
    public Result<Long> modifyInventory(@Valid @RequestBody AdminCollectionModifyParam param) {
        CollectionModifyInventoryRequest request = new CollectionModifyInventoryRequest();
        request.setIdentifier(UUID.randomUUID().toString());
        request.setCollectionId(param.getCollectionId());
        request.setQuantity(param.getQuantity());
        CollectionModifyResponse response = collectionManageFacadeService.modifyInventory(request);
        if (response.getSuccess()) {
            return Result.success(response.getCollectionId());
        } else {
            return Result.error(response.getResponseCode(), response.getResponseMessage());
        }
    }


    /**
     * 修改商品价格
     * @param param
     * @return
     */
    @PostMapping("/modifyPrice")
    public Result<Long> modifyPrice(@Valid @RequestBody AdminCollectionModifyParam param) {
        CollectionModifyPriceRequest request = new CollectionModifyPriceRequest();
        request.setIdentifier(UUID.randomUUID().toString());
        request.setCollectionId(param.getCollectionId());
        request.setPrice(param.getPrice());
        CollectionModifyResponse response = collectionManageFacadeService.modifyPrice(request);
        if (response.getSuccess()) {
            return Result.success(response.getCollectionId());
        } else {
            return Result.error(response.getResponseCode(), response.getResponseMessage());
        }
    }

    /**
     * 查询藏品列表信息
     * @param state
     * @param keyWord
     * @param pageSize
     * @param currentPage
     * @return
     */
    @GetMapping("/collectionList")
    public MultiResult<CollectionVO> collectionList(@NotBlank String state, String keyWord, int pageSize, int currentPage) {
        CollectionPageQueryRequest collectionPageQueryRequest = new CollectionPageQueryRequest();
        collectionPageQueryRequest.setState(state);
        collectionPageQueryRequest.setKeyword(keyWord);
        collectionPageQueryRequest.setCurrentPage(currentPage);
        collectionPageQueryRequest.setPageSize(pageSize);
        PageResponse<CollectionVO> pageResponse = collectionManageFacadeService.pageQuery(collectionPageQueryRequest);
        return MultiResultConvertor.convert(pageResponse);
    }
}
